package com.lgy.ms.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

public class JktAESUtil {

    public static String encrypt(String strKey, String strIn) {
        try {
            SecretKeySpec skeySpec = getKey(strKey);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(strIn.getBytes("UTF-8"));

            return JktBase64.encode(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String strKey, String strIn) throws Exception {
        if (StringUtil.isEmpty(strKey) || StringUtil.isEmpty(strIn)) {
            return null;
        }
        try {
            SecretKeySpec skeySpec = getKey(strKey);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decode(strIn);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "UTF-8");
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static SecretKeySpec getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[16]; // 创建一个空的16位字节数组（默认值为0）

        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

        return skeySpec;
    }

    /**
     * 构建健康通微信后台获取openId的请求参数
     * @param url 回调地址
     * @param accountId 公众号Id
     */
    public static String genGetWXOpenIdParam (String url, String accountId) throws Exception {
        String param = "{'accountid':'" + accountId +"','url':'"+ url +"'}";
        String key = "kmcnkle";
        String p = encrypt(key, param);
        p = URLEncoder.encode(p, "utf-8");
        return p;
    }

    /**
     * 获取健康通微信后台的返回的数据
     */
    public static JSONObject getWXBackResult (String aesData) throws Exception {
        String key = "kmcnkle";
        String plainData = decrypt(key, aesData);
        return JSON.parseObject(plainData);
    }

}
